<template>
  <el-table style="width: 100%,overflow: hidden" :data="labelList" :row-class-name="rowClassName" :row-key="className" class="endSessionTable" size="mini">
    <el-table-column  :label="$t('configLazyLoad.channel.endSessionTypeName')" class="label-name">
      <template scope="scope">
        <div class="row_line" :class="scope.row.level === 1 ? '' : scope.row.level === 2 ? 'row_tr_2' : 'row_tr_3'">
            <span class="do_icon" @click.stop="showLabel(scope.$index, scope.row)" v-show="!scope.row.status">
              <i :class="scope.row.level === 3 ? '' : scope.row.flag ? 'icon iconfont icon-zuixiaohua' : 'icon iconfont icon-zhankai'"></i>
            </span>
            <span style="margin-left: 10px" v-if="!scope.row.status">{{ scope.row.name }}</span>
            <span v-if="scope.row.status" :class = "{is_error: addBorderFlag===true}">
              <el-input v-model.trim="scope.row.name"  :placeholder="$t('configLazyLoad.channel.limit30')" :maxlength="30" class="edit_end_session_input" style="width: 170px;display:inline-block"></el-input>
              <div style="display: inline-block" class="addLabel"><span @click.stop="handleChannel(scope.$index, scope.row)">{{$t('public.cancel')}}</span><span @click.stop="handleSave(scope.$index, scope.row)">{{$t('public.save')}}</span></div>
            </span>
          </div>
      </template>
    </el-table-column>
    <el-table-column :label="$t('public.operate')" width="300px">
      <template scope="scope">
        <div v-show="scope.row.name && !scope.row.status" class="operate-btn">
          <span @click.stop="handleEdit(scope.$index, scope.row)">{{$t('public.edit2')}}</span>
          <span @click.stop="handleAddLabel(scope.$index, scope.row, '2')" v-show="scope.row.level === 1">{{$t('configLazyLoad.channel.addTwoLevelLabels')}}</span>
          <span @click.stop="handleAddLabel(scope.$index, scope.row, '3')" v-show="scope.row.level === 2">{{$t('configLazyLoad.channel.addThreeLevelLabels')}}</span>
          <span @click.stop="handleDisabled(scope.$index, scope.row)" class="delete">{{$t('public.delete')}}</span>
        </div>
      </template>
    </el-table-column>
  </el-table>
</template>
<script>
  import { deepClone } from '@utils/m7Utils.js'
  export default {
    name: 'EndSessionTreeTable',
//    stopAddFlag     当正在编辑添加的时候不让进行别的操作
//    addBorderFlag   为true是正在编辑
    data () {
      return {
//        labelList: [],
        maxLevel: 0,
        stopAddFlag: false,
        addBorderFlag: false,
        loading2: false,
        oldList: []
      }
    },
    props: {
      tableData: {
        type: Array,
        default () {
          return []
        }
      },
      searchLabelName: {
        type: String,
        default: ''
      },
      searchLabelRandom: {
        type: Number,
        default: 0
      },
      doAddRandom: {
        type: Number,
        default: 0
      },
      refreshflag: {
        type: Number,
        default: 0
      }
    },
    watch: {
//      监控数据变化，进行搜索数据
      searchLabelRandom () {
        this.searchLabel()
      },
      refreshflag (newFlag, old) {
        if (newFlag < 1 && newFlag > 0) {
          this.refreshTable()
        } else if (newFlag > 1) {
          this.stopAddFlag = false
          this.addBorderFlag = false
          this.refreshTable()
        }
        this.searchLabel()
      },
      doAddRandom () {
        this.handleAddOneLabel()
      }
    },
    methods: {
//     搜索标签，控制一级标签的显示隐藏
      searchLabel () {
        let flag = false
        this.labelList.forEach((item) => {
          if (item.status) {
            flag = true
          }
        })
        if (flag) {
          this.$message.error(this.$t('configLazyLoad.channel.searchWebchatLabelTips'))
          return
        }
        this.labelList.forEach((item) => {
          if ((item.level === 1) && document.getElementsByClassName(item.keyStr + '').length) {
            document.getElementsByClassName(item.keyStr + '')[0].style.display = 'table-row'
          }
        })
        let nextarray = []
        let KeyStr = []
        nextarray = this.labelList.filter((item) => {
          if (item.name.indexOf(this.searchLabelName) !== -1) {
            return item
          }
        })
        let n = []
        nextarray.forEach((item) => {
          KeyStr.push(item.keyStr.split('-')[0])
        })
        KeyStr.forEach((item) => {
          if (n.indexOf(item) === -1) {
            n.push(item)
          }
        })
        for (var i = 0; i < this.labelList.length; i++) {
          this.maxLevel = this.labelList[i].level > this.maxLevel ? this.labelList[i].level : this.maxLevel
          if (this.labelList[i].level !== 1 && document.getElementsByClassName(this.labelList[i].keyStr + '').length) {
            document.getElementsByClassName(this.labelList[i].keyStr + '')[0].style.display = 'none'
          }
          this.labelList[i].flag = false
        }
        this.labelList.forEach((item) => {
          if (n.indexOf(item.keyStr) === -1 && (item.level === 1) && document.getElementsByClassName(item.keyStr + '').length) {
            document.getElementsByClassName(item.keyStr + '')[0].style.display = 'none'
          }
        })
      },
//      展开
      unfolded (index, row) {
        let nextarray = []
        nextarray = this.labelList.filter((item) => {
          let a = item.keyStr.split('-')
          let str = ''
          for (let i = 0; i < row.level; i++) {
            str += a[i] + '-'
          }
          return item.keyStr.length > row.keyStr.length && (str.substring(0, str.length - 1) === row.keyStr) && item.level === row.level + 1
        })
        console.log(nextarray)
        nextarray.forEach((label) => {
          document.getElementsByClassName(label.keyStr)[0].style.display = 'table-row'
        })
        row.flag = true
      },
//      收起
      folded (index, row) {
        // 收起下级
        let nextarray = []
        nextarray = this.labelList.filter((item) => {
          let a = item.keyStr.split('-')
          let str = ''
          for (let i = 0; i < row.level; i++) {
            str += a[i] + '-'
          }
          return item.keyStr.length > row.keyStr.length && (str.substring(0, str.length - 1) === row.keyStr)
        })
        console.log(nextarray)
        nextarray.forEach((label) => {
          if (label.level === row.level + 1 && label.level < this.maxLevel) {
            label.flag = false
          }
          document.getElementsByClassName(label.keyStr)[0].style.display = 'none'
        })
        row.flag = false
      },
//      添加一级标签
      handleAddOneLabel () {
        if (this.stopAddFlag) {
          this.addBorderFlag = true
          return
        }
        this.stopAddFlag = true
//        level 1级
//        flag 控制加减号
        let obj = {
          keyStr: '',
          key: '',
          level: 1,
          name: '',
          lastLevel: '',
          status: true,
          flag: false
        }
        this.labelList.push(obj)
        this.inputFocus()
      },
//      添加二级／三级标签
      handleAddLabel (index, row, leavelNum) {
        if (this.stopAddFlag) {
          this.addBorderFlag = true
          return
        }
        this.stopAddFlag = true
        this.unfolded(index, row)
        let nextarr = []
        nextarr = this.labelList.filter((item) => {
          return item.keyStr.length > row.keyStr.length && item.keyStr.indexOf(row.keyStr) !== -1
        })
        let insertIndex = 0
        let keyStr = []
        if (nextarr.length !== 0) {
          for (let i = 0; i < this.labelList.length; i++) {
            if (nextarr[nextarr.length - 1].keyStr === this.labelList[i].keyStr) {
              insertIndex = i
              keyStr = this.labelList[i].keyStr.split('-')
              break
            }
          }
        } else {
          keyStr = row.keyStr.split('-')
          insertIndex = index
        }
        let obj = {
          keyStr: '',
          key: '',
          level: leavelNum,
          name: '',
          lastLevel: row.levelStr,
          status: true,
          flag: false
        }
        if (row.level === 1) {
          obj.keyStr = keyStr.length > 1 ? keyStr[0] + '-' + (parseInt(keyStr[1]) + 1) : keyStr[0] + '-' + 1
        } else if (row.level === 2) {
          obj.keyStr = keyStr.length > 2 ? keyStr[0] + '-' + keyStr[1] + '-' + (parseInt(keyStr[2]) + 1) : keyStr[0] + '-' + keyStr[1] + '-' + 1
        }
        this.labelList.splice(insertIndex + 1, 0, obj)
        this.inputFocus()
//        this.labelList.push(obj)
      },
//      取消操作
      handleChannel (index, row) {
        this.stopAddFlag = false
        this.addBorderFlag = false
        row.key ? row.status = false : this.labelList.splice(index, 1)
      },
      rowClassName ({row, index}) {
        return '' + row.keyStr
      },
//      通过keyStr添加唯一的className
      className (row, index) {
        return '' + row.keyStr
      },
//      展开／收起操作
      showLabel (index, row) {
        let flag = false
        if (row.flag) {
          this.labelList.forEach((item) => {
            if (item.key === '' || item.status === true) {
              if (row.keyStr.split('-').length < item.keyStr.split('-').length) {
                let _data = item.keyStr.substring(0, item.keyStr.lastIndexOf('-'))
                if (_data.indexOf(row.keyStr) !== -1) {
                  flag = true
                }
              }
            }
          })
          if (flag) {
            return
          }
          this.folded(index, row)
        } else {
          this.unfolded(index, row)
        }
        this.oldList = deepClone(this.labelList)
      },
//      编辑标签
      handleEdit (index, row) {
        if (this.stopAddFlag) {
          this.addBorderFlag = true
          return
        }
        row.status = true
        this.stopAddFlag = true
        this.inputFocus()
      },
//      删除
      handleDisabled (index, row) {
        let num = 0
        this.labelList.forEach((item) => {
          let arr = item.keyStr.split('-')
          if (arr.length < 2) {
            ++num
          }
        })
//        一级结束标签不得少于一条
        if (num < 2 && index === 0) {
          this.$message.error(this.$t('configLazyLoad.channel.mustHaveEndSessionType'))
          return
        }
        this.$confirm(this.$t('configLazyLoad.channel.confirmDeletEndSession'), this.$t('public.tip'), {
          confirmButtonText: this.$t('public.confirm'),
          cancelButtonText: this.$t('public.cancel'),
          cancelButtonClass: 'primary_btn',
          confirmButtonClass: 'primary_btn',
          type: 'warning'
        }).then(() => {
          this.oldList = deepClone(this.labelList)
          this.$emit('delete', row)
        })
      },
//      刷新table
      refreshTable () {
        this.$nextTick(() => {
          for (var i = 0; i < this.labelList.length; i++) {
            this.maxLevel = this.labelList[i].level > this.maxLevel ? this.labelList[i].level : this.maxLevel
            this.labelList[i].flag = false
            this.labelList[i].status = false
            if (this.labelList[i].level !== 1) {
              document.getElementsByClassName(this.labelList[i].keyStr + '')[0].style.display = 'none'
              document.getElementsByClassName(this.labelList[i].keyStr + '')[0].className += (' level' + this.labelList[i].level)
            }
          }
          for (var k = 0; k < this.labelList.length; k++) {
            let that = this
            console.log(this.oldList)
            that.oldList.forEach((item) => {
              if (item.key === that.labelList[k].key) {
                that.labelList[k].flag = item.flag
                if (that.labelList[k].flag) {
                  that.unfolded(0, that.labelList[k])
                }
              }
            })
          }
          this.stopAddFlag = false
          this.addBorderFlag = false
          this.loading2 = false
        })
      },
//      保存
      handleSave (index, row) {
        this.oldList = deepClone(this.labelList)
        this.$emit('save', row)
      },
//      编辑框获得焦点
      inputFocus () {
        this.$nextTick(() => {
          document.getElementsByClassName('edit_end_session_input')[0].children[0].focus()
        })
      }
    },
    computed: {
      labelList () {
        return this.tableData
      }
    },
    beforeMount () {
      this.stopAddFlag = false
      this.addBorderFlag = false
    },
    mounted () {
      this.refreshTable()
    }
  }
</script>
<style lang="stylus" scoped>
  @import "../../../../../assets/common.styl"
  .tree-table
    margin 10px 20px
  .addLabel
    span
      cursor pointer
      color $c-main
      margin-left 10px
  .row_padding
    padding-left 16px
  .operate-btn
    color $c-main
    span
      margin-left 10px
      cursor pointer
  .row_line
    display inline-block
  .row_tr_2
    padding-left 26px
  .row_tr_3
    padding-left 52px
  .endSessionTable
    overflow hidden
  .do_icon
    cursor pointer
  .delete
    color $c-pink
</style>
